/**
 * 
 */
package com.example.radioclub.music.adapter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.client.RestTemplate;

import com.example.radioclub.R;
import com.example.radioclub.data.Constants;
import com.example.radioclub.music.interfaces.IRestMusic;
import com.example.radioclub.music.tasks.RestCertificateDownloader;
import com.example.radioclub.music.tasks.RestUserDetailsDownloader;
import com.example.radioclub.types.ChartSong;
import com.example.radioclub.utilities.FunctionUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This adapter controls list of music, layout, and behavior.
 * 
 * @author wizard
 * 
 */
public class MusicAdapter extends SimpleAdapter implements IRestMusic, OnItemClickListener {
	private final String TAG = Constants.APP_TAG + "Music List Adapter";

	private Context context;
	private ArrayList<ChartSong> musicList = null;
	private String jsonMusicString = null;
	private ProgressDialog progressDialog;
	private RestTemplate mapiRestClientTemplate, mapiRestUserTemplate;
	private RestCertificateDownloader restCerfiticateDownloader;
	private RestUserDetailsDownloader restUserDetailsDownloader;
	private String melOnUserId = null;
	private String channelCode = null;
	private AlertDialog.Builder builder = null;
	private AlertDialog alert = null;
	private WebView playerView = null;
	
	/**
	 * An adapter to maintain music list.
	 * 
	 * @param context context from Activity on which this adapter is placed.
	 * @param jsonString String in JSON format as its music contents to be fetched.
	 * @param mapiRestClientTemplate a template containing client's authentication to access
	 * 			certain contents from MelOn.
	 * @param mapiRestUserTemplate a template containing user's authentication to access
	 * 			certain contents from MelOn.
	 * @param channelCode a channel code but don't worry about this yet.
	 * @param view a streaming control panel and please ignore this.
	 */
	public MusicAdapter(Context context, String jsonString, RestTemplate mapiRestClientTemplate, RestTemplate mapiRestUserTemplate, String channelCode, WebView view) {
		super(context, null, 0, new String[] {}, new int[] {});
		this.context = context;
		this.jsonMusicString = jsonString;
		this.musicList = FunctionUtils.getMusicListFromJson(jsonString);
		this.mapiRestClientTemplate = mapiRestClientTemplate;
		this.mapiRestUserTemplate = mapiRestUserTemplate;
		this.channelCode = channelCode;
		this.playerView = view;
		
		// Obtaining user details for streaming needs is begun here.
		this.restUserDetailsDownloader = new RestUserDetailsDownloader(mapiRestUserTemplate, this);
		this.restUserDetailsDownloader.execute();
		this.progressDialog = ProgressDialog.show(this.context, "Please wait.", "Loading your personal details.");
	}
	
	public ArrayList<ChartSong> getMusicList() {
		return musicList;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return musicList.size();
	}
	
	@Override
	public boolean isEnabled(int position) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int finPosition = position;
		final ChartSong chartSong = this.musicList.get(finPosition);
		LayoutInflater inflater = LayoutInflater.from(this.context);
		View musicLayout = inflater.inflate(R.layout.music_layout, null);

		TextView singer = (TextView) musicLayout.findViewById(R.id.music_playlist_element_singer);
		singer.setText(chartSong.getArtistName());
		TextView song = (TextView) musicLayout.findViewById(R.id.music_playlist_element_title);
		song.setText(chartSong.getSongName());
		
		ImageButton speakerButton = (ImageButton) musicLayout.findViewById(R.id.stream_this_song);
		speakerButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.i(TAG, "Speaker button is pressed");

				builder = new AlertDialog.Builder(context);
				builder.setTitle("Which one?").setMessage("Free or Paid?");
				builder.setPositiveButton("Paid", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								if(melOnUserId != null) {
									try {
										restCerfiticateDownloader = new RestCertificateDownloader(mapiRestClientTemplate, "521490", chartSong.getSongId() + "", channelCode, "M", MusicAdapter.this);
										restCerfiticateDownloader.execute();
										progressDialog = ProgressDialog.show(context, "Please wait.", "Getting certificate...");
									} catch (Exception e) {
										e.printStackTrace();
										Log.i(TAG, e.getMessage());
									}									
								} else {
									Toast.makeText(context, "Oops! It looks like MelOn doesn't have you as its customer.", Toast.LENGTH_SHORT).show();
								}
							}
						});
				builder.setNegativeButton("Free", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();

								playerView.getSettings().setJavaScriptEnabled(true);
								playerView.getSettings().setPluginsEnabled(true);
								playerView.getSettings().setPluginState(PluginState.ON);
								playerView.setWebChromeClient(new WebChromeClient() {
									@Override
									public void onProgressChanged(WebView view, int progress) {
										((Activity) context) .setProgress(progress);
									}
								});
								playerView.setWebViewClient(new WebViewClient() {

									@Override
									public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
										Toast.makeText(context, "Oh no! " + description, Toast.LENGTH_SHORT).show();
									}

									@Override
									public boolean shouldOverrideUrlLoading(WebView view, String url) {
										// TODO Auto-generated method stub
										Toast.makeText(context, "Overriding Url Loading...", Toast.LENGTH_SHORT).show();
										view.loadUrl("http://www.google.com/");
										return true;
									}
								});
								// web.loadUrl("https://www.youtube.com");
								// web.loadUrl("file:///android_asset/www/player.html");
								playerView.loadData(FunctionUtils.createHtmlPageNoCertificate(chartSong.getSongId() + "", channelCode), "text/html", "utf-8");
							}
						});
				alert = builder.create();
				alert.show();
			}
		});

		ImageButton addListButton = (ImageButton) musicLayout.findViewById(R.id.add_this_to_playlist);
		addListButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Log.i(TAG, "Add to list button is pressed");
			}
		});

		LinearLayout layout_container = (LinearLayout) musicLayout.findViewById(R.id.music_layout_container);
		layout_container.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle("Music details");
				builder.setItems(
						new String[] {
								"Album ID = " + chartSong.getAlbumId() + "",
								"Album Name = " + chartSong.getAlbumName(),
								"Artist ID = " + chartSong.getArtistId() + "",
								"Artist Name = " + chartSong.getArtistName(),
								"Available? " + chartSong.getAvailableStatus() + "",
								"Mod? " + chartSong.getMod() + "",
								"Playtime = " + chartSong.getPlayTime() + "",
								"Previous Ranking = " + chartSong.getPreviousRanking() + "",
								"Ranking = " + chartSong.getRanking() + "",
								"RBT Status = " + chartSong.getRBTStatus() + "",
								"Self Lyrics? " + chartSong.getSelfLyricStatus() + "",
								"Ala Carte Status = " + chartSong.getSellAlacarteStatus() + "",
								"Sell DRM Status = " + chartSong.getSellDrmStatus() + "",
								"Sell Non DRM Status = " + chartSong.getSellNonDrmStatus() + "",
								"Sell Stream Status = " + chartSong.getSellStreamStatus() + "",
								"Song ID =" + chartSong.getSongId() + "",
								"Title =" + chartSong.getSongName() }, null);
				builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						});
				builder.create().show();
			}
		});
		return musicLayout;
	}

	@Override
	public void onCertificateDownloadFinished(String result) {
		// TODO Auto-generated method stub		
		if (this.progressDialog.isShowing())
			this.progressDialog.dismiss();
		
		if(this.alert.isShowing()) {
			this.alert.dismiss();
		}

		if (result != null && result != "null") {
			Log.i(TAG, result);
			try {
				String certificate = new JSONObject(result).getString("message");
				final Activity activity = (Activity) this.context;
	
				playerView.getSettings().setJavaScriptEnabled(true);
				playerView.getSettings().setPluginsEnabled(true);
				playerView.getSettings().setPluginState(PluginState.ON);
				playerView.setWebChromeClient(new WebChromeClient() {
					@Override
					public void onProgressChanged(WebView view, int progress) {
						activity.setProgress(progress);
					}
				});
				playerView.setWebViewClient(new WebViewClient() {
	
					@Override
					public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
						Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
					}
	
					@Override
					public boolean shouldOverrideUrlLoading(WebView view, String url) {
						// TODO Auto-generated method stub
						Toast.makeText(activity, "Overriding Url Loading...", Toast.LENGTH_SHORT).show();
						view.loadUrl("http://www.google.com/");
						return true;
					}
				});
				// web.loadUrl("https://www.youtube.com");
				// web.loadUrl("file:///android_asset/www/player.html");
				playerView.loadData(FunctionUtils.createHtmlPage(certificate), "text/html", "utf-8");
	
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		Toast.makeText(context, "Toast!", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onUserDetailDownloadFinished(String result) {
		// TODO Auto-generated method stub
		if(this.progressDialog.isShowing()) this.progressDialog.dismiss();
		if(result != null) {
			try {
				this.melOnUserId = new JSONObject(result).getString("melon_uid");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.i(TAG, e.getMessage());
			}
		}
		
	}

	@Override
	public void onClientAuthenticationFinished(Object[] result) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDownloadFinished(Object object) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onGenreDownloadFinished(String result) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onMusicFinished(String result) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSearchingFinished(String result) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onServerAuthFinished(RestTemplate result) {
		// TODO Auto-generated method stub
		
	}
}
